package com.qc.wintrax.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.PolylineOptions;
import com.qc.wintrax.BaseActivity;
import com.qc.wintrax.R;
import com.qc.wintrax.WTApplication;
import com.qc.wintrax.model.Distance;
import com.qc.wintrax.utils.GpsCorrect;
import com.qc.wintrax.utils.LogUtil;
import com.qc.wintrax.utils.ToastUtil;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import greendao.LineName;
import greendao.MapInfo;
import greendao.MarkerInfo;

/**
 * @author fujianxiong
 * @Description:(地图选取地址) create at  10:05
 **/
public class MapActivity extends BaseActivity implements LocationSource, AMapLocationListener {

    @Bind(R.id.map)
    MapView mapView;
    @Bind(R.id.distance_view)
    TextView distanceView;
    @Bind(R.id.name_et)
    EditText nameEt;
    @Bind(R.id.stop_btn)
    Button stopBtn;
    @Bind(R.id.start_puse_btn)
    Button startPuseBtn;

    private AMap aMap;
    private Marker marker;// 定位雷达小图标
    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private double longitude;
    private double latitude;
    private List<LatLng> points = new ArrayList<LatLng>();
    private List<Distance> distanceList = new ArrayList<Distance>();
    private double a;
    private double b;
    private double address;
    private double alldistance;
    private LatLng startLatlng;
    private Marker markers;
    private ArrayList<MarkerOptions> markerList = new ArrayList<MarkerOptions>();
    private ArrayList<Marker> mList = new ArrayList<Marker>();
    private LatLng mlatlng;
    private List<MapInfo> mapInfoList = new ArrayList<MapInfo>();
    private List<MapInfo> newmapInfoList = new ArrayList<MapInfo>();
    private List<MarkerInfo> markerInfos = new ArrayList<MarkerInfo>();
    private List<MarkerInfo> newmarkerInfos = new ArrayList<MarkerInfo>();

    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
    Date curDate = new Date(System.currentTimeMillis());//获取当前时间
    String str = formatter.format(curDate);
    private String name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        ButterKnife.bind(this);
        initView();
        LogUtil.e(str);
        nameEt.setText(str);
//        WTApplication.getInstance().getGSDaoSession().getMapAddressDao().insertInTx(list);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
    }

    private void initView() {
        if (aMap == null) {
            aMap = mapView.getMap();
            aMap.moveCamera(CameraUpdateFactory.zoomTo(30));
//            setUpMap();
//            geocoderSearch = new GeocodeSearch(this);
//            geocoderSearch.setOnGeocodeSearchListener(this);
        }
        aMap.setOnMapLongClickListener(new AMap.OnMapLongClickListener() {
            @Override
            public void onMapLongClick(LatLng latLng) {
                mlatlng = latLng;
                latitude = mlatlng.latitude;
                longitude = mlatlng.longitude;
                LogUtil.e("获取的经纬度----" + latitude + "-----" + longitude);
                Intent intent = new Intent(context, MoreMarkerActivity.class);
                startActivityForResult(intent, 1);
//                latLngToAddress(new LatLonPoint(latLng.latitude, latLng.longitude));
//                setMarker(latLng);
            }
        });
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                for (int i = 0; i < mList.size(); i++) {
                    if (marker.equals(mList.get(i))) {
                        if (aMap != null) {
//                            if (markerTAG == 0) {
////                                jumpPoint(marker, i);
//                                Toast.makeText(context, "跳到相机功能", Toast.LENGTH_SHORT).show();
//                                LogUtil.e("跳到相机功能" + i);
//                                markerTAG = 1;
//                            } else {
//                                Toast.makeText(context, "查看图片", Toast.LENGTH_SHORT).show();
//                                LogUtil.e("查看图片");
//                                markerTAG = 0;
//                            }
                        }
                    }
                }
                return false;
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                String biaoji = data.getStringExtra("biaoji");
                LogUtil.e("获取的标记是----" + biaoji);
                setMarker(mlatlng, biaoji);
                MarkerInfo markerInfo = new MarkerInfo();
                markerInfo.setMarker_latitude(latitude);
                markerInfo.setMarker_longitude(longitude);
                markerInfo.setMarker_titleName(biaoji);
                markerInfos.add(markerInfo);

//                WTApplication.getGSDaoSession().getMarkerInfoDao().insert(markerInfo);
            }
        }
    }

    private void setMarker(LatLng latlon, String title) {
//        aMap.clear();
        deactivate();
//        View markerView = LayoutInflater.from(context).inflate(R.layout.marker_view, null);
        // 设置标注物的图片
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.map_zuobiao);
//        BitmapDescriptor bitmaps = BitmapDescriptorFactory.fromBitmap(bit);
        // 构建MarkerOption，用于在地图上添加Marker
        MarkerOptions options = new MarkerOptions().position(latlon).icon(bitmap).title(title);
        // 在地图上添加Marker，并显示
        options.snippet(latlon.toString());
        options.draggable(true);
        options.perspective(true);
        options.draggable(true);
        markerList.add(options);
        markers = aMap.addMarker(options);
        mList.add(markers);
        aMap.addMarkers(markerList, true);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        deactivate();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation != null && amapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                //定位成功回调信息，设置相关消息
//                LogUtil.e("开始获取的经纬度--a--" + a);
//                LogUtil.e("开始获取的经纬度--b--" + b);
                if (a > 0 && b > 0) {
                    startLatlng = new LatLng(a, b);
//                    LogUtil.e("获得的对象---000---" + startLatlng);
                }
                amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                a = amapLocation.getLatitude();//获取纬度
                b = amapLocation.getLongitude();//获取经度
//                latlang = GpsCorrect.transform(a,b);
//                a1 = latlang[0];
//                b1 = latlang[1];
                LogUtil.e("获得的对象---纠偏后---" + a + "-----" + b);

                LogUtil.e("结束获取的经纬度--a--" + a);
                LogUtil.e("结束获取的经纬度--b--" + b);
                LatLng endLatlng = new LatLng(a, b);
                amapLocation.getAccuracy();//获取精度信息
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(amapLocation.getTime());
                df.format(date);//定位时间
                amapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                amapLocation.getCountry();//国家信息
                amapLocation.getProvince();//省信息
                amapLocation.getCity();//城市信息
                amapLocation.getDistrict();//城区信息
                amapLocation.getStreet();//街道信息
                amapLocation.getStreetNum();//街道门牌号信息
                amapLocation.getCityCode();//城市编码
                amapLocation.getAdCode();//地区编码
                if (startLatlng.equals(endLatlng)) {
                    LogUtil.e("看看走的哪里2222222222222222222222");
                } else {
                    MapInfo mapInfo = new MapInfo();
                    mapInfo.setMap_title(name);
                    mapInfo.setMap_latitude(a);
                    mapInfo.setMap_longitude(b);
                    mapInfoList.add(mapInfo);

                    LogUtil.e("看看走的哪里1111111111111111");
                    // 计算量坐标点距离
                    if (startLatlng != null) {
                        address = AMapUtils.calculateLineDistance(startLatlng, endLatlng);
                        BigDecimal bd = new BigDecimal(address);
                        double disStr = bd.setScale(1, BigDecimal.ROUND_HALF_DOWN).doubleValue();
                        alldistance = alldistance + disStr;
                        double dis = bd.setScale(1, BigDecimal.ROUND_HALF_DOWN).doubleValue();
                        distanceView.setText(dis + " m ");
                        LogUtil.e("结束获取的距离--disStr-0000-" + dis);
                        LatLng latLng = new LatLng(a, b);
                        points.add(latLng);
                        aMap.addPolyline(new PolylineOptions().color(Color.rgb(18, 184, 246)).
                                addAll(points).useGradient(true).width(10));
                    }
                }
            } else {
                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
            }
        }
    }

    private void setUpMap() {
        ArrayList<BitmapDescriptor> giflist = new ArrayList<BitmapDescriptor>();
//        giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point1));
//        giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point2));
//        giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point3));
//        giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point4));
//        giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point5));
//        giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point6));
        marker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f).icons(giflist).period(50));
        // 自定义系统定位小蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
//        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.map_zuobiao));// 设置小蓝点的图标
//        myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
//         myLocationStyle.anchor(int,int)//设置小蓝点的锚点
        myLocationStyle.strokeWidth(0);// 设置圆形的边框粗细
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setMyLocationEnabled(true);
        // 设置定位的类型为定位模式 ，可以由定位 LOCATION_TYPE_LOCATE、
        // 跟随 LOCATION_TYPE_MAP_FOLLOW 或地图根据面向方向旋转 LOCATION_TYPE_MAP_ROTATE
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().isCompassEnabled();
        aMap.getUiSettings().setCompassEnabled(true);
        aMap.getUiSettings().setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_RIGHT);
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            // 设置定位监听
            mlocationClient.setLocationListener(this);
            // 设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            // 设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    @OnClick({R.id.stop_btn, R.id.start_puse_btn})
    public void onClick(View view) {
        name = nameEt.getText().toString();
        switch (view.getId()) {
            case R.id.stop_btn:
                mapView.onPause();
                deactivate();
                LineName lineName = new LineName();
                lineName.setMap_title(name);
                long id = WTApplication.getGSDaoSession().getLineNameDao().insert(lineName);
                ToastUtil.show(context, "获取的主键" + id);
                for (int i = 0; i < mapInfoList.size(); i++) {
                    MapInfo mapInfo = mapInfoList.get(i);
                    double a = mapInfo.getMap_latitude();
                    double b = mapInfo.getMap_longitude();
                    String name = mapInfo.getMap_title();
                    MapInfo mapInfo1 = new MapInfo();
                    mapInfo1.setMap_latitude(a);
                    mapInfo1.setMap_longitude(b);
                    mapInfo1.setMap_title(name);
                    mapInfo1.setLine_id(id);
                    newmapInfoList.add(mapInfo1);
                }
                WTApplication.getGSDaoSession().getMapInfoDao().insertInTx(newmapInfoList);
                for (int a = 0; a < markerInfos.size(); a++) {
                    MarkerInfo markerInfo = markerInfos.get(a);
                    double aa = markerInfo.getMarker_latitude();
                    double bb = markerInfo.getMarker_longitude();
                    String names = markerInfo.getMarker_titleName();
                    MarkerInfo info = new MarkerInfo();
                    info.setLine_id(id);
                    info.setMarker_latitude(aa);
                    info.setMarker_longitude(bb);
                    info.setMarker_titleName(names);
                    newmarkerInfos.add(info);
                }
                WTApplication.getGSDaoSession().getMarkerInfoDao().insertInTx(newmarkerInfos);
                WTApplication.getInstance().finishActivity();
                mapView.onDestroy();
                break;
            case R.id.start_puse_btn:
                if (startPuseBtn.getText().toString().equals("开始")) {
                    WTApplication.getInstance().setConfig("name", name);
                    setUpMap();
                    startPuseBtn.setText("暂停");
                } else if (startPuseBtn.getText().toString().equals("暂停")) {
                    mapView.onPause();
                    deactivate();
                    startPuseBtn.setText("开始");
                }
                break;
        }
    }

//    /**
//     * @author fujianxiong
//     * @Description:(地址转经纬度) create at  10:46
//     **/
//    private void addressToLatLng(String address) {
//        GeocodeQuery query = new GeocodeQuery(address, cityCode);// 第一个参数表示地址，第二个参数表示查询城市，中文或者中文全拼，citycode、adcode，
//        geocoderSearch.getFromLocationNameAsyn(query);// 设置同步地理编码请求
//    }
//
//    /**
//     * 响应逆地理编码
//     */
//    public void latLngToAddress(LatLonPoint latLonPoint) {
//        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 50,
//                GeocodeSearch.AMAP);// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
//        geocoderSearch.getFromLocationAsyn(query);// 设置同步逆地理编码请求
////        setMarker(new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude()));
//    }

//    /**
//     * 地理编码查询回调
//     */
//    @Override
//    public void onGeocodeSearched(GeocodeResult result, int rCode) {
//        if (rCode == 0) {
//            if (result != null && result.getGeocodeAddressList() != null
//                    && result.getGeocodeAddressList().size() > 0) {
//                GeocodeAddress address = result.getGeocodeAddressList().get(0);
//                LogUtil.e("address" + address);
////                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
////                        AMapUtil.convertToLatLng(address.getLatLonPoint()), 19));
//                double latitudes = address.getLatLonPoint().getLatitude();
//                double longitudes = address.getLatLonPoint().getLongitude();
//                city = address.getCity();
//                province = address.getProvince();
//                district = address.getDistrict();
//                latitude = latitudes + "";
//                longitude = longitudes + "";
//                setMarker(new LatLng(latitudes, longitudes),null);
//            } else {
////                ToastUtil.show(context, R.string.no_result);
//            }
//        } else if (rCode == 27) {
////            ToastUtil.show(context, R.string.error_network);
//        } else if (rCode == 32) {
////            ToastUtil.show(context, R.string.error_key);
//        } else {
////            ToastUtil.show(context, getString(R.string.error_other) + rCode);
//        }
//    }


//    /**
//     * 逆地理编码回调
//     */
//    @Override
//    public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
//        if (rCode == 0) {
//            if (result != null && result.getRegeocodeAddress() != null
//                    && result.getRegeocodeAddress().getFormatAddress() != null) {
////                LogUtil.e(result.getRegeocodeAddress().getFormatAddress()+"");
//                inputAddress = result.getRegeocodeAddress().getFormatAddress() + "";
////                addressToLatLng(result.getRegeocodeAddress().getFormatAddress()+"");
//            } else {
////                ToastUtil.show(context, R.string.no_result);
//            }
//        } else if (rCode == 27) {
////            ToastUtil.show(context, R.string.error_network);
//        } else if (rCode == 32) {
////            ToastUtil.show(context, R.string.error_key);
//        } else {
////            ToastUtil.show(context,
////                    getString(R.string.error_other) + rCode);
//        }
//    }
}
